import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginBySMS, loginByPassword } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))

  // 登录方法
  const login = async (params, type = 'sms') => {
    try {
      const res = type === 'sms' 
        ? await loginBySMS(params)
        : await loginByPassword(params)
      
      token.value = res.token
      userInfo.value = res.user
      
      // 持久化存储
      localStorage.setItem('token', res.token)
      localStorage.setItem('userInfo', JSON.stringify(res.user))
      
      return res
    } catch (err) {
      logout()
      throw err
    }
  }

  // 登出方法
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  return { token, userInfo, login, logout }
})